//
//  ARPickerImageView.m
//  AwesomeRecorder
//
//  Created by Xing on 2019/11/29.
//  Copyright © 2019 Xing. All rights reserved.
//

#import "PickerVideoView.h"
#import <AssetsLibrary/AssetsLibrary.h>
#import "PickerVideoAddPhotoCell.h"
#import "AddVideoSingleModel.h"
//#import <GKPhotoBrowser/GKPhotoBrowser.h>
#import "LXReorderableCollectionViewFlowLayout.h"
#import <AVKit/AVKit.h>

@interface PickerVideoView()
<UICollectionViewDelegate,
UICollectionViewDataSource>

@property(nonatomic,strong) NSMutableArray *selectedImgsInfo;
@property(nonatomic,strong) UIView *bottomLine;

@property(nonatomic,strong) UIImage *removeIcon;//删除按钮
@property(nonatomic,assign) CGPoint removeIconOffset;

@end

@implementation PickerVideoView

+ (CGFloat)viewHeight {
    
    return 110;
}

- (instancetype)init {
    
    return [self initWithFrame:CGRectZero];
}

- (instancetype)initWithFrame:(CGRect)frame {
    
    self = [super initWithFrame:frame];
    
    if (self) {
        
        [self initData];
        [self addViews];
    }
    
    return self;
}

- (void) initData {
    
    _margin = 10;
    _addIcon = [UIImage imageNamed:@"img_add.png"];
    _removeIcon = [UIImage imageNamed:@"img_remove.png"];
    _removeIconOffset = CGPointMake(5, -5);
    _maxCount = 9;
    _editable = YES;
    _videoArr = [NSMutableArray array];
}

- (void) addViews {
    
    self.backgroundColor = [UIColor whiteColor];
    
    LXReorderableCollectionViewFlowLayout *layout = [[LXReorderableCollectionViewFlowLayout alloc] init];
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    _collectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 0, self.width, self.height) collectionViewLayout:layout];
    _collectionView.dataSource = self;
    _collectionView.delegate = self;
    _collectionView.backgroundColor = [UIColor clearColor];
    _collectionView.showsHorizontalScrollIndicator = NO;
    
    [_collectionView registerClass:[PickerVideoAddPhotoCell class] forCellWithReuseIdentifier:@"PickerImageAddPhotoCell"];
    
    [self addSubview:_collectionView];
}

- (void) clear {
    
    [_videoArr removeAllObjects];
    [_collectionView reloadData];
}

- (void)refreshView {
    
    WEAKSELF
    dispatch_async(dispatch_get_main_queue(), ^{
        [weakSelf.collectionView reloadData];
    });
    
    if (self.selViewDidRefreshView){
        self.selViewDidRefreshView(_videoArr.count);
    }
}

- (void)resetRemoveIcon:(UIImage *)removeIcon offset:(CGPoint)offset {
    
    if (removeIcon) {
        _removeIcon = removeIcon;
    }
    
    _removeIconOffset = offset;
    
    [self refreshView];
}

#pragma mark -
#pragma mark actions

- (void) closeActionWithIndex:(NSInteger)index {
    
    if (index < _videoArr.count) {
        WEAKSELF
        [Utils showAlertWithTitle:LocalStr(@"Are you sure you want to remove the photo?") content:nil targetVC:self.targetVC dismissBlock:^(NSInteger idx) {
            if (idx == 1) {
                [weakSelf.videoArr removeObjectAtIndex:index];
                [weakSelf refreshView];
                if (weakSelf.selViewDidChange) {
                    weakSelf.selViewDidChange();
                }
            }
        } cancelButton:LocalStr(@"Cancel") otherButtons:@[LocalStr(@"Sure")]];
    }
}

- (void)browseActionWithIndex:(NSInteger)index {
    
//    NSMutableArray *imgArr = [NSMutableArray array];
//    for (int i=0; i<_videoArr.count; i++) {
//        GKPhoto *photo = [GKPhoto new];
//        PickerVideo *obj = [_videoArr objectAtIndex:i];
//        photo.image = obj.coverImage;
//        [imgArr addObject:photo];
//    }
//
//    GKPhotoBrowser *browser = [GKPhotoBrowser photoBrowserWithPhotos:imgArr currentIndex:0];
//    browser.showStyle = GKPhotoBrowserShowStyleNone;
//    [browser showFromVC:self.targetVC];
    
    
    PickerVideo *obj =  [_videoArr objectAtIndex:index];
    
//    WEAKSELF
//    PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
//    options.version = PHImageRequestOptionsVersionCurrent;
//    options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
//
//    PHImageManager *manager = [PHImageManager defaultManager];
//
//    [manager requestAVAssetForVideo:obj.assert options:options resultHandler:^(AVAsset * _Nullable asset, AVAudioMix * _Nullable audioMix, NSDictionary * _Nullable info) {
//
//        AVURLAsset *urlAsset = (AVURLAsset *)asset;
//        NSURL *url = urlAsset.URL;
//
//        [weakSelf playVideoWithUrl:url];
//    }];
    
    [self playVideoWithUrl:obj.fileURL];
}

- (void)playVideoWithUrl:(NSURL *)url {
    
    AVPlayerViewController *playerVC = [[AVPlayerViewController alloc] init];
    playerVC.player= [[AVPlayer alloc]initWithURL:url];
    playerVC.modalPresentationStyle = UIModalPresentationFullScreen;
    
    
    [self.targetVC presentViewController:playerVC animated:YES completion:^{
        if ([playerVC isReadyForDisplay]) {
            [playerVC.player play];
        }
    }];
}

- (void) newPhotoAction {
    
    WEAKSELF
    
    [[AddVideoSingleModel sharedInstance] showAddMultiPhotoWinWithTargetVC:self.targetVC complete:^(PickerVideo *video) {
        [weakSelf didReceiveVideoAction:video];
    }];
    
    if (self.selViewDidShowPickerView) {
        self.selViewDidShowPickerView();
    }
}


/**
 获取到最终结果的图片
 
 @param object object
 */
- (void) didReceiveVideoAction:(PickerVideo *)object {
    
    if (!object) {
        return;
    }
    
    [self.videoArr addObject:object];
    [self refreshView];
    
    if (self.selViewDidChange) {
        self.selViewDidChange();
    }
    
    WEAKSELF
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (weakSelf.collectionView.contentSize.width>weakSelf.collectionView.width) {
            NSInteger row = weakSelf.videoArr.count<weakSelf.maxCount?weakSelf.videoArr.count:weakSelf.videoArr.count-1;
            [weakSelf.collectionView scrollToItemAtIndexPath:[NSIndexPath indexPathForRow:row inSection:0] atScrollPosition:UICollectionViewScrollPositionLeft animated:YES];
        }
    });
}

- (void)setEditable:(BOOL)editable {
    
    _editable = editable;
    
    [self refreshView];
}

#pragma mark -
#pragma mark collectionView delegate
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    if (_videoArr.count < _maxCount) {
        if (_editable) {
            return _videoArr.count + 1;
        } else {
            return _videoArr.count;
        }
    } else {
        return _videoArr.count;
    }
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    WEAKSELF
    
    NSInteger row = indexPath.row;
    
    PickerVideoAddPhotoCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"PickerImageAddPhotoCell" forIndexPath:indexPath];
    cell.removeIcon = _removeIcon;
    cell.addIcon = _addIcon;
    cell.cornerRadius = 0;
    cell.removeIconOffset = _removeIconOffset;
    cell.cellDidClickCloseAction = ^(NSInteger index){
        [weakSelf closeActionWithIndex:index];
    };
    
    if (row < _videoArr.count) {
        PickerVideo *video = [_videoArr objectAtIndex:row];
        [cell refreshWithVideoObject:video isAddIcon:NO editable:_editable index:row];
    } else {
        [cell refreshWithVideoObject:nil isAddIcon:YES editable:_editable index:row];
    }
    
    return cell;
}

- (void) collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath {
    
    NSInteger row = indexPath.row;
    
    if (row < _videoArr.count) {
        [self browseActionWithIndex:row];
    }else{
        [self newPhotoAction];
    }
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    CGFloat width = 90;
    
    return CGSizeMake(width, width);
}

- (UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout insetForSectionAtIndex:(NSInteger)section {
    
    int margin = (int)_margin;
    return UIEdgeInsetsMake(margin, margin, margin, margin);
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section {
    
    return (int)_margin;
}

- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section {
    
    return (int)_margin;
}

#pragma mark -
#pragma mark LXReorderableCollectionViewFlowLayout ios8

- (BOOL) collectionView:(UICollectionView *)collectionView
 canMoveItemAtIndexPath:(nonnull NSIndexPath *)indexPath {
    
    NSInteger row = indexPath.row;
    
    if (row >= _videoArr.count) {
        return NO;
    } else {
        return YES;
    }
}

- (BOOL) collectionView:(UICollectionView *)collectionView
        itemAtIndexPath:(NSIndexPath *)fromIndexPath
     canMoveToIndexPath:(NSIndexPath *)toIndexPath {
    
    if (toIndexPath.row >= _videoArr.count) {
        return NO;
    } else {
        return YES;
    }
}

- (void) collectionView:(UICollectionView *)collectionView
        itemAtIndexPath:(NSIndexPath *)fromIndexPath
    willMoveToIndexPath:(NSIndexPath *)toIndexPath {
    
}

- (void) collectionView:(UICollectionView *)collectionView
        itemAtIndexPath:(NSIndexPath *)fromIndexPath
     didMoveToIndexPath:(NSIndexPath *)toIndexPath {
    
    PickerVideo *dic = [_videoArr objectAtIndex:fromIndexPath.row];
    [_videoArr removeObjectAtIndex:fromIndexPath.row];
    [_videoArr insertObject:dic atIndex:toIndexPath.row];
    
    [collectionView reloadData];
    
    if (self.selViewDidChange) {
        self.selViewDidChange();
    }
}

- (void) collectionView:(UICollectionView *)collectionView
                 layout:(UICollectionViewLayout *)collectionViewLayout
willBeginDraggingItemAtIndexPath:(NSIndexPath *)indexPath {
    
}

- (void) collectionView:(UICollectionView *)collectionView
                 layout:(UICollectionViewLayout *)collectionViewLayout
didBeginDraggingItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
}

- (void) collectionView:(UICollectionView *)collectionView
                 layout:(UICollectionViewLayout *)collectionViewLayout
willEndDraggingItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
}

- (void) collectionView:(UICollectionView *)collectionView
                 layout:(UICollectionViewLayout *)collectionViewLayout
didEndDraggingItemAtIndexPath:(NSIndexPath *)indexPath {
    
    
}

- (void) dealloc {
    
    _removeIcon = nil;
    _addIcon = nil;
}

@end
